package api

import (
	"fmt"
	"kyland.com/eagle/manager"
	"net/http"
	"os"
)

func Upload(ctx *Context) {
	file, err := ctx.FormFile("file")
	if err != nil {
		ctx.jsonSuccess("get parameter failed")
	}

	fileName := fmt.Sprintf("/opt/data/video/%s", file.Filename)
	if fileExists(fileName) {
		manager.SendMessage(fileName)
		ctx.jsonSuccess("file already exists")
	} else {
		if err := ctx.SaveUploadedFile(file, fileName); err != nil {
			ctx.jsonFailure("upload failed")
		} else {
			go manager.Upload(fmt.Sprintf("/opt/data/video/%s", file.Filename))
			ctx.jsonSuccess("upload success")
		}
	}
}

func Download(ctx *Context) {

	name := ctx.paramString("name")
	filename := fmt.Sprintf("/opt/data/result/%s", name)
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		ctx.String(http.StatusInternalServerError, "Error file not exist: %v", err)
	}

	downName := fmt.Sprintf("attachment; filename=%s", filename)
	ctx.Header("Content-Disposition", downName) // 设置下载文件名
	ctx.File(filename)
	//ctx.jsonSuccess("download success")
}

func fileExists(filename string) bool {
	_, err := os.Stat(filename)
	// 如果文件存在，err 会是 nil
	if err == nil {
		return true
	}
	// 如果文件不存在，会返回一个错误，可以使用 os.IsNotExist 来检查
	return !os.IsNotExist(err)
}
